package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 生成订单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders) {
        // orders  order_detail
        // 0、获取用户id
        Long userId = UserHolder.get();
        // 1、查询购物车数据：select * from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(qw);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            return R.error("购物车为空，不能下单");
        }

        // 2、查询用户数据 select * from user where id = ?
        User user = userService.getById(userId);

        // 3、根据地址id查询地址数据 select * from address_book where id = ?
        Long addressBookId = orders.getAddressBookId();
        AddressBook byId = addressBookService.getById(addressBookId);
        if(addressBookId == null){
           return R.error("用户地址信息有误，不能下单");
        }
        //4.使用IdWorker.getid方法生成订单号
        long orderId = IdWorker.getId();
        //5.新建BigDecimal对象用于记录总价(amount)
        BigDecimal amount = new BigDecimal(0);
        //6遍历购物车数据;
        //6.1新建订单明细表对象
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail =new OrderDetail();
            //6.2将购物车数据复制到订单明细表中
            BeanUtil.copyProperties(shoppingCart,orderDetail);
            //6.3单独设置orderld;
            orderDetail.setOrderId(orderId);
            //6.4单独设置amountjine  数量*单价
            BigDecimal price =shoppingCart.getAmount();//获取单价
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());//获取数量
            orderDetail.setAmount(price.multiply(number));
            //把计算好的总价填入进去
            amount=amount.add(orderDetail.getAmount());
            orderDetailMapper.insert(orderDetail);
        }
        //保存订单数据
        orders.setId(orderId);//订单id
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAmount(amount);//总金额
        orders.setUserId(userId);//用户id
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserName(user.getName());//用户名
        orders.setConsignee(byId.getConsignee());//收货人
        orders.setPhone(byId.getPhone());//收货人联系电话
        orders.setAddress(
                (byId.getProvinceName() == null ? "" : byId.getProvinceName())
                        + (byId.getCityName() == null ? "" : byId.getCityName())
                        + (byId.getDistrictName() == null ? "" : byId.getDistrictName())
                        + (byId.getDetail() == null ? "" : byId.getDetail()));//省+市+区域+详细地址
        ordersMapper .insert(orders);
        // 6、删除当前用户的购物车数据
        // delete from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(ShoppingCart::getUserId,userId);
        shoppingCartMapper.delete(qw1);
        return R.success("下单成功");
    }

//    /**
//     * 分页查询
//     * @param page
//     * @param pageSize
//     * @return
//     */
//    @GetMapping("/userPage")
//    public R page( Integer page,Integer pageSize){
//        //创建page对象,设置当前也的大小
//        Page<Orders> pageInfo =new Page<>(page,pageSize);
//        //获取用户id
//        Long userId = UserHolder.get();
//        //设置查询条件
//        LambdaQueryWrapper<Orders>qw =new LambdaQueryWrapper<>();
//        qw.eq(Orders::getUserId,userId);
//        //执行查询
//        ordersService.page(pageInfo,qw);
//        //获取查询条数
//        long total = pageInfo.getTotal();
//        //获取查询列表
//        List<Orders> records = pageInfo.getRecords();
//        Map<String,Object> map =new HashMap<>();
//        map.put("total",total);
//        map.put("records",records);
//        return R.success(map);
//    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */

    @GetMapping("/userPage")
public R pageInfo(Integer page, Integer pageSize) {
    Page pageInfo = new Page(page, pageSize);
    LambdaQueryWrapper<Orders> qwpage = new LambdaQueryWrapper<>();
    qwpage.orderByDesc(Orders::getOrderTime);
    ordersService.page(pageInfo,qwpage);

    List<Orders> records = pageInfo.getRecords();
    List<OrdersDto> ordersDtos = records.stream().map((item) -> {
        OrdersDto ordersDto = new OrdersDto();
        BeanUtil.copyProperties(item, ordersDto);

        LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
        qw.eq(OrderDetail::getOrderId, ordersDto.getId());

        List<OrderDetail> orderDetails = orderDetailService.list(qw);
        ordersDto.setOrderDetails(orderDetails);

        int sumNum = orderDetailService.count(qw);
        ordersDto.setSumNum(sumNum);

        return ordersDto;
    }).collect(Collectors.toList());

    long total = pageInfo.getTotal();
    Map data = new HashMap<>();
    data.put("records",ordersDtos);
    data.put("total",total);
    return R.success(data);
    }
}
